package com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util

//import com.zhi.syc.data.util.ASStoreUtil
import android.app.Application
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.AESCryptUtil
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.apiHostCommonCombine
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.event.IAnalyticsEvent
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.http.HttpHelper
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsConstants
import com.facebook.appevents.AppEventsLogger
import com.google.gson.Gson
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Calendar
import java.util.Currency
import java.util.Locale
import java.util.TimeZone

object FacebookUtil {

    private var mAppEventsLogger: AppEventsLogger =
        AppEventsLogger.newLogger(ProjectApplication.context)

    /**
     * 初始化facebook模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        try {
            FacebookSdk.sdkInitialize(context)
            AppEventsLogger.activateApp(context)
            saveS2SInfo()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存facebook s2s信息
     */
    fun saveS2SInfo() {
        val params = HashMap<String, Any>().createApiAction().apply {
            put("path", "zRmXAtKGubCJpGwwGsSaw")
            put("advertiser_tracking_enabled", AnalyticsUtil.getAdEnabled().toString())
            put("application_tracking_enabled", AnalyticsUtil.getAdEnabled().toString())
            put("install_referrer", AnalyticsUtil.getInstallReferrer())
            put("installer_package", ProjectApplication.mPackageName)
            put("app_data", getAppData())
        }
        val content = Gson().toJson(params).trim()
        println("aes before：\n $content")

        // 加密后
        val body: String = AESCryptUtil.encryptDefault(content)
        println("aes after：\n $body")
        HttpHelper.postData(apiHostCommonCombine(), body)
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent(event: IAnalyticsEvent) {
        try {
            when (event) {
                IAnalyticsEvent.AT_REGISTER -> {
                    val params = Bundle()
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_REGISTRATION_METHOD,
                        event.name
                    )
                    mAppEventsLogger.logEvent(
                        AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION,
                        params
                    )
                }

                IAnalyticsEvent.AT_BASIC -> {
                    val params = Bundle()
                    params.putString(AppEventsConstants.EVENT_PARAM_LEVEL, event.name)
                    mAppEventsLogger.logEvent(
                        AppEventsConstants.EVENT_NAME_ACHIEVED_LEVEL,
                        params
                    )
                }

                IAnalyticsEvent.AT_CONTACT -> {
                    val params = Bundle()
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_TYPE,
                        event.name
                    )
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_SEARCH_STRING,
                        event.name
                    )
                    params.putInt(AppEventsConstants.EVENT_PARAM_SUCCESS, 1)
                    mAppEventsLogger.logEvent(
                        AppEventsConstants.EVENT_NAME_SEARCHED, params
                    )
                }

                IAnalyticsEvent.AT_REV_CARD -> {
                    val params = Bundle()
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_TYPE,
                        event.name
                    )
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_ID,
                        event.name
                    )
                    params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "UGX")
                    mAppEventsLogger.logEvent(
                        AppEventsConstants.EVENT_NAME_VIEWED_CONTENT,
                        1.0,
                        params
                    )

                }

                IAnalyticsEvent.AT_LOAN_APPLY -> {
                    val params = Bundle()
                    params.putInt(AppEventsConstants.EVENT_PARAM_NUM_ITEMS, 1)
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_TYPE,
                        event.name
                    )
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_ID,
                        event.name
                    )
                    params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "UGX")
                    mAppEventsLogger.logPurchase(
                        BigDecimal.valueOf(1),
                        Currency.getInstance("UGX"),
                        params
                    )

                }

                IAnalyticsEvent.AT_REPAY -> {
                    val params = Bundle()
                    params.putString(
                        AppEventsConstants.EVENT_PARAM_CONTENT_ID,
                        event.name
                    )
                    params.putInt(AppEventsConstants.EVENT_PARAM_SUCCESS, 1)
                    mAppEventsLogger.logEvent(
                        AppEventsConstants.EVENT_NAME_COMPLETED_TUTORIAL,
                        params
                    )
                }

                else -> {}
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取总存储大小
     */
    fun getTotalRom(): String {
        var totalRom = ""//ASStoreUtil.getCashTotal(ProjectApplication.instance)
        if (totalRom.endsWith("TB")) {
            totalRom = totalRom.replace("TB".toRegex(), "")
            totalRom =
                BigDecimal(totalRom).multiply(BigDecimal(1024)).stripTrailingZeros().toPlainString()
        } else if (totalRom.endsWith("GB")) {
            totalRom = totalRom.replace("GB".toRegex(), "")
        } else if (totalRom.endsWith("MB")) {
            totalRom = totalRom.replace("MB".toRegex(), "")
            totalRom = BigDecimal(totalRom).divide(BigDecimal(1024), RoundingMode.HALF_UP)
                .stripTrailingZeros().toPlainString()
        }
        return totalRom
    }

    /**
     * 获取可用存储大小
     */
    fun getAvalidableRom(): String {
        var totalRom = ""
//            ASStoreUtil.getCashCanUse(ProjectApplication.instance)
        if (totalRom.endsWith("TB")) {
            totalRom = totalRom.replace("TB".toRegex(), "")
            totalRom =
                BigDecimal(totalRom).multiply(BigDecimal(1024)).stripTrailingZeros().toPlainString()
        } else if (totalRom.endsWith("GB")) {
            totalRom = totalRom.replace("GB".toRegex(), "")
        } else if (totalRom.endsWith("MB")) {
            totalRom = totalRom.replace("MB".toRegex(), "")
            totalRom = BigDecimal(totalRom).divide(BigDecimal(1024), RoundingMode.HALF_UP)
                .stripTrailingZeros().toPlainString()
        }
        return totalRom
    }

    /**
     * 组装回传参数
     */
    fun getAppData(): String {

        val jsonObject = JSONObject()
        jsonObject.put("advertiser_tracking_enabled", AnalyticsUtil.getAdEnabled().toString())
        jsonObject.put("application_tracking_enabled", AnalyticsUtil.getAdEnabled().toString())
        jsonObject.put("install_referrer", AnalyticsUtil.getInstallReferrer())
        jsonObject.put("installer_package", ProjectApplication.mPackageName)

        val extinfo = mutableListOf<String>()
        //0 extinfo version a2
        extinfo.add("a2")
        //1 app package name
        extinfo.add(ProjectApplication.mPackageName)
        //2 short version
        extinfo.add(ProjectApplication.mAppVersion)
        //3 long version
        extinfo.add("${ProjectApplication.mAppVersion} long")
        //4 os version
        extinfo.add(Build.VERSION.RELEASE + "")
        //5 device model name
        extinfo.add(Build.MODEL)
        //6 locale
        extinfo.add(Locale.getDefault().toString())
        //7 timezone abbr
        extinfo.add(Calendar.getInstance().timeZone.getDisplayName(false, TimeZone.SHORT))
        //8 carrier
        extinfo.add("")
//        extinfo.add(ASGeneralUtil.getSimOperatorName(ProjectApplication.instance))
        //9 screen width
        extinfo.add(Resources.getSystem().displayMetrics.widthPixels.toString())
        //10 screen height
        extinfo.add(Resources.getSystem().displayMetrics.heightPixels.toString())
        //11 screen density
        extinfo.add(Resources.getSystem().displayMetrics.density.toString())
        //12 cpu core
        extinfo.add(Runtime.getRuntime().availableProcessors().toString())
        //13 external storage size in GB
        extinfo.add(getTotalRom())
        //14 free space on external storage in GB
        extinfo.add(getAvalidableRom())
        //15 device timezone
        extinfo.add(Calendar.getInstance().timeZone.displayName)

        jsonObject.put("extinfo", extinfo)

        return jsonObject.toString()
    }
}